<script setup lang="ts">
/**
 * @name ShiftEnergyStatistics
 * @description 班次能耗统计
 */
import StatisticsPageWrapper from '../components/StatisticsPageWrapper/StatisticsPageWrapper.vue'
import type { Query } from '../components/type'
import { useQueryLists } from './ShiftEnergyStatistics'

const [loading, setLoading] = useState(true)

const {
  tabsData,
  columns,
  tableData,
  x,
  y,
  l,
  pieData,
  emptyPie,
  setEnergyData,
  getEnergyTypes,
  getEnergyData,
  findIndicatorNumber,
} = useQueryLists()

async function queryChangeHandler(o: Query) {
  // console.log('query-change: ', o);
  const pointId = o.pointId!
  if (!pointId)
    return

  const type = o.type
  const dataTime = o.time

  setLoading(true)
  try {
    await getEnergyTypes({
      pointId: o.pointId!,
      dataTime: o.time,
      type: o.type,
    })
    // 如果没有能源种类就不查能耗数据了
    if (unref(tabsData).length === 0) {
      setLoading(false)
      return
    };
    await nextTick()

    const energyType = o.energyType
    const indicatorNumber = findIndicatorNumber(energyType!)
    if (!indicatorNumber) {
      console.warn(`[findIndicatorNumber] energyType: ${energyType}, indicatorNumber: ${indicatorNumber}`)
      setEnergyData([])
      return
    }

    await getEnergyData({
      dataTime,
      type,
      indicatorNumber,
      // indicatorNumber: 'EU92.MI.002300.EY',
    })
  }
  catch (e) {
  }
  finally {
    setLoading(false)
  }
}

/** 切换能源卡片时只需要更新能耗数据 */
async function energyChangeHandler(o: Query) {
  // console.log('energy-change: ', o);
  const pointId = o.pointId!
  if (!pointId)
    return
  // 如果没有能源种类就不查能耗数据了
  if (unref(tabsData).length === 0)
    return

  const type = o.type
  const dataTime = o.time
  const energyType = o.energyType

  const indicatorNumber = findIndicatorNumber(energyType!)

  if (!indicatorNumber) {
    console.warn(`[findIndicatorNumber] energyType: ${energyType}, indicatorNumber: ${indicatorNumber}`)
    setEnergyData([])
    return
  }
  setLoading(true)
  try {
    await getEnergyData({
      dataTime,
      type,
      indicatorNumber,
      // indicatorNumber: 'EU92.MI.002300.EY',
    })
  }
  catch (e) {
  }
  finally {
    setLoading(false)
  }
}
onMounted(() => {
  // 防止query-change与energy-change同时不触发
  setLoading(false)
})
</script>

<template>
  <StatisticsPageWrapper
    :loading="loading"
    :tabs-props="{
      data: tabsData,
    }"
    :bar-props="{ x, y, l }"
    :pie-props="pieData"
    :table-props="{
      columns,
      data: tableData,
    }"
    :chart-height="300"
    :empty-pie="emptyPie"
    @query-change="o => queryChangeHandler(o)"
    @energy-change="o => energyChangeHandler(o)"
  />
</template>
